package com.boot.down.util;

import com.boot.down.common.Const;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author dell
 */
public class CookieUtil {


    private static final String COOKIE_DOMAIN = "192.168.1.191";

    private static final String COOKIE_NAME = "MY_COOKIE_IN_PROJECT";

    //读取cookie

    public static String readCookieInRequest(HttpServletRequest request){
        Cookie[] cks = request.getCookies();
        if(cks != null){
            for(Cookie cookie : cks){
                if(COOKIE_NAME.equals(cookie.getName())){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    //写入cookie

    public static void writeCookieInResponse(HttpServletResponse response, String token){

        Cookie cookie = new Cookie(COOKIE_NAME, token);
        cookie.setDomain(COOKIE_DOMAIN);
        cookie.setPath("/");
        //cookie有效期 1天， 不存不会写入硬盘， 而只写入内存
        cookie.setMaxAge((int) Const.EFFECTIVE_TIME);

        response.addCookie(cookie);
    }

    //删除cookie

    public static void delCookie(HttpServletRequest request, HttpServletResponse response){

        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if(COOKIE_NAME.equals(cookie.getName())){
                    cookie.setDomain(COOKIE_DOMAIN);
                    cookie.setPath("/");
                    //0代表删除
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                    return;
                }
            }
        }
    }

}
